package com.example.rentsystem.servlet.pages;

import com.example.rentsystem.entity.User;
import com.example.rentsystem.service.AdviceService;
import com.example.rentsystem.service.impl.AdviceServiceImpl;
import com.example.rentsystem.utils.ThymeleafUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.thymeleaf.context.Context;

import java.io.IOException;

@WebServlet("/advice")
public class AdviceServlet extends HttpServlet {

    AdviceService service;

    @Override
    public void init() throws ServletException {
        service = new AdviceServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            req.getSession().setAttribute("login-first", true);
            resp.sendRedirect("login");
            return;
        }
        String advice_info = "";
        String advice_info_style = "";
        if (session.getAttribute("advice") != null) {
            advice_info = "长度不能大于50!";
            advice_info_style = "color: red;font-weight: bold;";
            session.removeAttribute("advice");
        }
        Context context = new Context();
        context.setVariable("user", user);
        context.setVariable("isAdmin", user.getRole().equals("admin"));
        context.setVariable("advice_info", advice_info);
        context.setVariable("advice_info_style", advice_info_style);
        if (user.getRole().equals("admin")) context.setVariable("list", service.getAdvices());
        ThymeleafUtil.process("advice.html", context, resp.getWriter());
    }
}
